package ruc.MongoDB.read;

import com.mongodb.client.MongoCollection;
import org.bson.Document;
import ruc.Consts.constant;
import ruc.utils.IOUtils;
import ruc.MongoDB.MongoDB_Common;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

public class MongoDB_DiffResSet {
    private static final int CLIENT = 15;
    private int bound, port;
    private String IP, dbName, tbName;

    public MongoDB_DiffResSet(String IP, int port, String dbName, String tbName, int bound) {
        this.IP = IP;
        this.port = port;
        this.dbName = dbName;
        this.tbName = tbName;
        this.bound = bound;
    }

    public void DiffResSetRead(int record[]) throws InterruptedException {
        Random ran = new Random();
        MongoCollection<Document> collection = MongoDB_Common.GetMongoCollection(IP, port, dbName, tbName);

        for(int i = 0; i < record.length; i++) {
            CountDownLatch CDL = new CountDownLatch(CLIENT);
            AtomicLong AL = new AtomicLong(0);
            for(int j = 0; j < CLIENT; j++) {
                int finalI = i;
                new Thread(()->{
                    long st_time = System.nanoTime();
                    collection.find().limit(record[finalI]).skip(ran.nextInt(bound));
                    AL.addAndGet(System.nanoTime() - st_time); //时间太短，转成ms有精度损失
                    CDL.countDown();
                }).start();
            }

            CDL.await();
            System.out.printf("[TSBench-D] >>>>> [MongoDB_DiffResSetRead] record Line : %d, threadNum: %d, response time : %d >>>>>\n", record[i], CLIENT, AL.longValue());
            IOUtils.WriteData(constant.GetWriteFilePath("MongoDB", "DiffResSet"),
                    new String[]{String.valueOf(record[i]), String.valueOf(CLIENT), AL.longValue()+"ns"});
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MongoDB_DiffResSet db = new MongoDB_DiffResSet(constant.IP, constant.MongoDB_port, constant.dbName, constant.Concurrent_tbName, constant.bound);
        db.DiffResSetRead(constant.RecordNum);
    }
}
